#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

using namespace std;

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        cout << "./main ip port" << endl;
        exit(1);
    }

    int port = atoi(argv[2]);
    string ip = argv[1];

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    int check = connect(listen_sock, (sockaddr *)&addr, sizeof(addr));
    if(check < 0)
    {
        cout << "CONNECT_ERR " << strerror(errno) << endl;
        exit(1);
    }
    string Str;

    int pid = fork();
    if(pid == 0)
    {
        while(1)
        {
            char buffer[1024];
            int Check = recv(listen_sock, buffer, 1023, 0);
            cout << buffer << endl;
            memset(buffer, 0, 1024);
            cout << "请输入》》" << endl;
        }
    }

    while (1)
    {
        cout << "请输入》》" << endl;
        cin >> Str;
        int Check = send(listen_sock, Str.c_str(), Str.size(), 0);
        if (Check > 0)
        {
            cout << "发送成功: " << Str << endl;
        }
        else
        {
            cout << "SEND_ERR" << strerror(errno) << endl;
        }
    }
    return 0;
}